<template>
  <div class="product">
    <!-- 搜索框 -->
    <div class="search">
      <template>
        <el-select v-model="searchValue"
                   filterable
                   clearable
                   remote
                   @blur="searchBlur"
                   @change="searchTextChange"
                   reserve-keyword
                   @clear="clear"
                   placeholder="请输入姓名,如果不更新,点击右侧搜索按钮"
                   :remote-method="remoteMethod"
                   :loading="loading">
          <el-option v-for="item in searchList"
                     :key="item.sId"
                     :label="item.name"
                     :value="item.name">
          </el-option>
        </el-select>
      </template>
      <!-- 搜索按钮 -->
      <el-button type="primary"
                 icon="el-icon-search"
                 @click="onSearchButtonClick"
                 plain></el-button>
      <!-- 添加按钮 -->
      <!-- <el-button type="primary"
                 @click="addStu"
                
                 :disabled="disabled">添加项目</el-button> -->
   
    <!-- Form -->
<el-button type="primary" @click="addStu()" v-hasPermission="'add'">添加项目</el-button>

<el-dialog center :title=tit :visible.sync="dialogFormVisible">
  <el-form :model="form">
  <el-form-item label="头像" :label-width="formLabelWidth" >
     
      <el-upload
  class="avatar-uploader"
  action="http://chst.vip/students/uploadStuAvatar"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="form.headimgurl" :src="form.headimgurl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
    </el-form-item>
    

    <el-form-item label="姓名" :label-width="formLabelWidth"  :rules="[
      { required: true}
    ]">
      <el-input v-model="form.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="项目地址" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.productUrl" autocomplete="off"></el-input>  
    </el-form-item>
     <el-form-item label="班级" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.class" autocomplete="off"></el-input>  
    </el-form-item>
     <el-form-item label="年龄" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.age" autocomplete="off"></el-input>  
    </el-form-item>
     <el-form-item label="城市" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.city" autocomplete="off"></el-input>  
    </el-form-item>
     <el-form-item label="学历" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.degree" autocomplete="off"></el-input>  
    </el-form-item>
     <el-form-item label="描述" :label-width="formLabelWidth" :rules="[
      { required: true}
    ]">
     <el-input v-model="form.description" autocomplete="off"></el-input>  
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="tit=='添加学员信息'?addStu1():editStu1()">确 定</el-button>
  </div>
</el-dialog>
 </div>
    <!-- 班级选择 -->
    <div class="select-class">
      <!-- 框框 -->
      <el-form>
        <el-form-item label="选择班级:">
          <el-select v-model="classes"
                     filterable
                     @visible-change="classVisible"
                     @change="classChange"
                     placeholder="请选择">
            <el-option label="全部"
                       value="all"></el-option>
            <el-option v-for="(item,index) in classOptions"
                       :key="index"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- 导出excel -->
    <div class="exportExcel">
      <el-button icon="iconfont iconexel"
                 @click="exportExcel">导出excel数据</el-button>
    </div>
    <!-- 表格 -->
    <div class="stu-table">
      <el-table :data="stuData"
                v-loading="loading"
                border  
                style="width: 100%">
        <el-table-column prop="headimgurl"
                         align="center"
                         label="头像"
                         width="80">
          <template slot-scope="scope">
            <el-avatar shape="square"
                       :size="50"
                       fit="fill"
                       :src="scope.row.headimgurl"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name"
                         align="center"
                         label="姓名"
                         width="180">
        </el-table-column>
        <el-table-column prop="class"
                         align="center"
                         label="班级">
        </el-table-column>
        <el-table-column prop="productUrl"
                         align="center"
                         label="项目">
        </el-table-column>
        <el-table-column align="center"
                         label="操作">
          <template slot-scope="{row}">
            <el-button type="primary"
                       class="btn"
                       icon="el-icon-view"
                     
                       @click="see(row)" v-hasPermission="'read'" >查看</el-button>
            <el-button type="primary"
                       class="btn"
                       icon="el-icon-edit"
                     
                       @click="editStu(row)" v-hasPermission="'edit'">编辑</el-button>
            <el-button type="danger"
                       class="btn"
                       icon="el-icon-delete"                      
                       @click="deleteStu(row)" v-hasPermission="'delete'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <!-- <div class="pagination">
      <el-pagination background
                     hide-on-single-page
                     layout="prev, pager, next"
                     @current-change="changePage"
                     :page-size="dataCount"
                     :total="total">
      </el-pagination>
    </div> -->
    <!-- dialog弹出框 -->
    <!-- <qf-dialog></qf-dialog> -->
  </div>
</template>
<script>
// import dialog from '../../../components/dialog'
import { getStuLists } from '@/api'
import { delStu, getStuList,searchStu ,addStuReq,editStuReq} from '../../../../api'
// import qee from 'qf-export-excel'
import qee from "qf-export-excel"

export default {
 
  data () {
    return {
      params: {
        class: '',
        count: 5
      },
      // dataPage: '', // 页码
      // dataCount: 5, // 每页展示的数量
      // total: 0, // 总共的数据条数
      classOptions: [],
      disabled: false,
      // 表格的数据对象
      stuData: [],
      // 表格加载动画控制
      loading: true,
      classes: '',
      searchList: [],
      searchValue: '',
      blurSearchValue: '',
      qf:true,
      tit:"",
      list: [],
       dialogFormVisible: false,
        form: {
          class: '',
          name: '',
          age: '',
          city: '',
          degree: '',
          productUrl:'',
          description: '',
          headimgurl: ''
         
        },
        formLabelWidth: '120px'
    
    }
  },
   created(){
this.updateStuTable()
  },
  methods: {
    // 分页器页码发生改变的时候触发的事件
    // changePage (page) {
    //   this.dataPage = page
    //   // 点击分页切换的时候 需要判断是否搜索了 如果搜索了 那么就应该在搜索结果中 进入第后面页码数据
    //   if (this.searchValue) {
    //     this.searchButton()
    //     return
    //   }
    //   this.updateStuTable(this.params)
    // },
    
// 导出表格
    exportExcel(){
let titlelist=[
  {
    title:"头像地址",
    key:"headimgurl"
  },
  {
    title:"项目",
    key:"productUrl"
  },
  {
    title:"班级",
    key:"class"
  },
  {
    title:"姓名",
    key:"name"
  }
]
let dataSource=[...this.stuData]  //表格数据数组  防止引用数据类型，加上...
qee(titlelist,dataSource,"学员数据")
    },
    // 班级选择框展开/收起触发的事件
    classVisible (isVisible) {
      //展开的时候需要获取数据
      //调用获取列表的方法
    if(isVisible){  //展开
getStuList()
.then(res=>{
  
  let norepeatArr=[]
  res.data.data.forEach(item=>{
    norepeatArr.push(item.class)
  })
  norepeatArr=Array.from(new Set(norepeatArr))
  this.classOptions=norepeatArr
  console.log(norepeatArr);
})
    }
    },
    // 选择班级
    classChange (query) {
    //  console.log("==="+query);
    //如果query是all代表要显示所有的数据，后台的设定是:class字段传空字符串就返回所有班级的数据，
    //所以以下用一个三元表达式来处理
    let classes=query==="all"?"":query   //全部为all
         //复用更新学员逻辑
     this.updateStuTable({page:1,count:10,classes})
    },
    onSearchButtonClick () {
      // 点击搜索按钮
      console.log(111);
    this.remoteMethod(this.blurSearchValue)
        this.searchTextChange()
    },
    // 搜索框失去焦点 保持输入框的内容
    searchBlur () {
      // 将存储好的输入框值 设置给select组件
      this.searchValue = this.blurSearchValue
      // this.searchTextChange( this.searchList)
    },
    // 编辑学员
    // editStu (row) {
    //   // this.$bus.$emit('editStuEvent', row)
    // },
    // 删除学员
    deleteStu (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'     
        }).then(() => {
         delStu(row.sId)
         .then(res=>{    
         {  
           if(res.data.state){
              this.$message({
            type: 'success',
            message: '删除成功!'
            
          })
            this.updateStuTable() 
           }else{
             this.$message.error("删除出错了哦 ！数据可能被别人删除了")
           }
         
          
         }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        
    
         })
     
    },
    // 增加学员
     handleAvatarSuccess(res, file) {
        this.form.headimgurl = URL.createObjectURL(file.raw);
      },
       beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
    addStu () {
      
       this.tit = "添加学员信息"
      this.dialogFormVisible = true

      
    },
    addStu1(){
      console.log(1);
      this.qf=true
      addStuReq(this.form)
      .then(res=>{
        if(res.data.state){
           this.$message({
          message: '恭喜你，成功添加一条数据',
          type: 'success'
        });
        this.dialogFormVisible=false
        this.updateStuTable()
        this.form={}
        }else{
            this.$message.error('没有添加成功');
        }
      })
    },
    editStu(row){
       this.qf=false
        this.tit = "编辑学员信息"
      this.dialogFormVisible = true
      console.log(row)
          this.form= { ...row }
         
console.log(this.form);

    
      
    },
    editStu1(){
       console.log(2);
editStuReq(this.form)
      .then(res=>{
        console.log(res)
        if(res.data.state){
           this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.dialogFormVisible=false
        this.updateStuTable()
        }else{
            this.$message.error('没有修改成功');
        }
      })
},
see(row){
  console.log(row);
  this.$router.push({path:'/StudentManager/studentProfile',query:{_id:row._id}})
},
    // 更新表格数据
    //参数初始化
    updateStuTable (params={count:10,page:1,classes:""}) {
      this.loading=true
     //发送请求获取学员数据
    getStuList(params).then(res=>{
  //获取数据成功
  this.stuData=res.data.data
  
  //关闭loading
  this.loading=false
})
       
    },
    clear (e) {
      this.updateStuTable()
     },
    // 搜索框选中值发生变化的事件
    searchTextChange (searchText) {
     console.log(this.searchList);
     this.stuData=this.searchList
    },
    remoteMethod (query) {
      this.blurSearchValue=query   //赋值三方变量进行输入框内容存储
      let key=query;
      let page=1;
      let count="";
      console.log(query);
      searchStu(page,count,key)
      .then(res=>{
        this.searchList=res.data.data
      })
    }
  },
  // mounted () {
  //   // 页面加载 获取表格数据
  //   this.updateStuTable(this.params)
  //   // this.$bus.$on('updateStuTable', () => {
  //   //   this.updateStuTable(this.params)
  //   // })
  // }
}
</script>
<style scoped>
  .search {
    line-height: 60px;
    text-align: left;
    margin: 20px 0;
  }
  .select-class {
    line-height: 40px;
    text-align: left;
    margin-bottom: 20px;
  }
  .stu-table .btn {
    width: 65px;
    height: 25px;
    padding: 0;
  }
  .pagination {
    margin-top: 20px;
  }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .exportExcel{
   text-align: right;
   margin-bottom: 16px;
 
  }
 .exportExcel .el-button{
      background: #409EFF;
      color: white;
  }
</style>